package io.github.harmonly.skyblock.util;

import java.text.DecimalFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.UUID;
import java.util.regex.Pattern;

public final class Utilities {

    private static final Pattern TOKEN_SPLITTER = Pattern.compile("(?<!\\\\)\\.");

    public static ZonedDateTime getDateTime(long timeStamp) {
        return Instant.ofEpochMilli(timeStamp).atZone(ZoneId.of("America/New_York"));
    }

    /**
     * Splits the input {@code key} into tokens, which are delimited by dots ({@code .}) that aren't
     * preceded by a backslash ({@code \}).
     */
    public static String[] tokenizeKey(String key) {
        return TOKEN_SPLITTER.split(key);
    }

    public static UUID uuidFromString(String uuidStr) {
        if (!uuidStr.contains("-")) {
            uuidStr = uuidStr.substring(0, 8) + "-"
                    + uuidStr.substring(8, 12) + "-"
                    + uuidStr.substring(12, 16) + "-"
                    + uuidStr.substring(16, 20) + "-"
                    + uuidStr.substring(20, 32);

        }
        return UUID.fromString(uuidStr);
    }

    public static String simplifiedUuid(String uuid) {
        return uuid.replaceAll("-", "");
    }

    public static String simplifiedUuid(UUID uuid) {
        return simplifiedUuid(uuid.toString());
    }

    public static String camelCase(String input) {
        StringBuilder result = new StringBuilder(input.length());
        boolean capitalizeNext = true;

        for (char c : input.toCharArray()) {
            if (c == ' ' || c == '_') {
                capitalizeNext = true;
                result.append(' ');
            } else if (capitalizeNext) {
                result.append(Character.toUpperCase(c));
                capitalizeNext = false;
            } else {
                result.append(Character.toLowerCase(c));
            }
        }

        return result.toString();
    }

    public static String formatLargeNumber(double number) {
        String suffix = "";
        if (number >= 1e9) {
            number /= 1e9;
            suffix = "B";
        } else if (number >= 1e6) {
            number /= 1e6;
            suffix = "M";
        } else if (number >= 1e3) {
            number /= 1e3;
            suffix = "k";
        }
        return new DecimalFormat("#.#").format(number) + suffix;
    }

    private Utilities() {
        throw new UnsupportedOperationException("Helper class should not be instantiated");
    }
}
